package com.shirley.netty.udp.server;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.CharsetUtil;

public class UdpServerInputMsgHandler extends SimpleChannelInboundHandler<DatagramPacket> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket dp) throws Exception {
        System.out.println("Get message from client" + ctx.channel().id() + ", msg: " + dp.content().toString(CharsetUtil.UTF_8));
        ctx.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer("Message had been gotten.", CharsetUtil.UTF_8),
        dp.sender()));

    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("Channel " + ctx.channel().id() + " actived.");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // (4)
        // Close the connection when an exception is raised.
        cause.printStackTrace();
        ctx.close();
    }
}
